package com.ymt.fmd.platform.web.action;

import com.ymt.fmd.appboot.prop.FmdProperties;
import com.ymt.fmd.platform.service.FmdService;
import com.ymt.fmd.util.Const;
import com.ymt.fmd.util.ModuleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;


/**
 * For form designer
 * @author fuzheng
 *
 */
@Controller
@RequestMapping("/view/platform/fmd")
@EnableConfigurationProperties(value = {FmdProperties.class})
public class FormDesignerAction {
    
	//logger
	private static Logger logger = Logger.getLogger(FormDesignerAction.class.getName());

	@Autowired
	private FmdProperties fmdProperties;

	@Autowired
	private Environment env;
	
	/**
	 * fmd service
	 */
	@Autowired
	private FmdService fmds;
	
	@RequestMapping(path="/design")
	public ModelAndView index(HttpServletRequest request,
							  @RequestParam(value = "f", required = false)String formid64,
							  @RequestParam(value = "v", required = false)String versionid64,
							  @RequestParam(value = "t", required = false)String formtype64) {
		Map<String, String> userDetail = (Map<String, String>) SecurityContextHolder.getContext().getAuthentication().getDetails();
		String lang = userDetail.get(Const.LANG);
		String loginName = userDetail.get(Const.LOGINNAME);

		String formid = decode(formid64);
		String versionid = decode(versionid64);
		String formtype = decode(formtype64);
		logger.finer("fmddesign lang="+lang);
		logger.finer("fmddesign loginName="+loginName);
		logger.finer("fmddesign formtype="+formtype);
		logger.finer("fmddesign formid="+formid);
		logger.finer("fmddesign versionid="+versionid);
		
		String[] profile = env.getActiveProfiles();
		String productionVersion = env.getProperty("bpmp.production-version", "0");
		String cdn = env.getProperty("bpmp.cdn", "/bpmp-resources");

		ModelAndView view = new ModelAndView("platform/fmd/designer/formdesigner");
		view.addObject("profile", profile[0]);
		view.addObject("productionVersion", productionVersion);
		view.addObject("cdn", cdn);
		view.addObject(Const.LANG, lang);

		// fmd specific
		
		//set formid and versionid
		if (formid!=null && versionid!=null) {
			view.addObject("formid", formid);
			view.addObject("versionid", versionid);
		} else {
			//TODO check formtype
			view.addObject("formtype", formtype);//form type for new form
		}
		
		boolean isEditor = formid==null ? true : fmds.isEditor(loginName, formid, versionid);
		view.addObject("isEditor", isEditor);

		final String moduleExcludes = null;//StringUtils.trim(Settings.getValue("fmd.filter.module.excludes"));

		//get layout modules
		String realPath = request.getServletContext().getRealPath("/");
		logger.finer("realPath="+realPath);
		//view.addObject("modules_path_layout", modules_path_layout);
		//view.addObject("modules_layout", ModuleUtil.getModuleNames(realPath, fmdProperties.getModulesPathLayout(), moduleExcludes));

		//get control modules
		//view.addObject("modulesControl", ModuleUtil.getModuleNames(realPath, fmdProperties.getModulesPathControl(), moduleExcludes));
		String moduleControls = env.getProperty("fmd.module-controls");
		view.addObject("moduleControls", asListString(moduleControls));

		view.addObject("fmdProperties", fmdProperties);
		view.addObject("cdnfmd", env.getProperty("fmd.cdn", "/bpmp-engine/fmd"));
		view.addObject("fmdCtx", env.getProperty("fmd.ctx"));
		view.addObject("ctxPath", request.getContextPath());

//        String displayName = userDetail.get(Const.DISPLAYNAME);
//        try {1
//            view.addObject(Const.LOGINNAME, Base64Utils.encodeToString(loginName.getBytes(Const.ENCODING)));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
		//view.addObject(Const.DISPLAYNAME, displayName);
		return view;
	}

	private String decode(String src) {
		try {
			if (src!=null) {
				return URLDecoder.decode(new String(Base64Utils.decodeFromString(src), Const.ENCODING), Const.ENCODING);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	private String asListString(String moduleControls) {
		String[] arr = moduleControls.split(",");
		StringBuilder rtn = new StringBuilder("[");
		for (String a : arr) {
			if (rtn.length()>1) {
				rtn.append(",");
			}
			rtn.append('"').append(a).append('"');
		}
		rtn.append("]");
		return rtn.toString();
	}
	
}
